const sending = require('koa-send')
const json = require('jsonwebtoken')
const { code } = require('../static/secret')
const upload = require('../config/setUpload')
const fs = require('fs-extra')
const path = require('path')
module.exports = {
  upload: async (ctx, next) => {
    const error = await upload.single('file')(ctx, next).then(res => res).catch(err => {
      console.log(err)
      return err
    })
    if (!error) {
      ctx.body = {
        status: 200,
        message: '上传成功',
        data: {}
      }
    } else {
      if (error.message === '文件名重复') {
        ctx.body = {
          status: 403,
          message: error.message,
          data: {}
        }
      }
    }
  },
  send: async (ctx, next) => {
    const token = ctx.headers.authorization.split(' ')[1]
    const info = await json.verify(token, code)
    ctx.verifyParams({ name: { type: 'string', required: 'true' } })
    const { name } = ctx.request.body
    if (!fs.pathExistsSync(`./upload/${info.username}/${name}`)) {
      ctx.body = {
        status: 404,
        message: '无此文件',
        data: {}
      }
    } else {
      console.log('hello')
      ctx.attachment(name)
      sending(ctx, './' + name, { root: path.resolve(__dirname, '..') + `/upload/${info.username}` })
        .then(res => {
          console.log(res)
          console.log('ow')
        })
        .catch(err => {
          console.log(err)
          ctx.body = {
            status: 403,
            message: err.message,
            data: {}
          }
        })
    }
  },
  show: async (ctx, next) => {
    const token = ctx.headers.authorization.split(' ')[1]
    const info = await json.verify(token, code)
    if (!fs.pathExistsSync(`./upload/${info.username}`)) {
      ctx.body = {
        status: 200,
        message: '此用户未上传过文件',
        data: {}
      }
    } else {
      const dir = await fs.readdir(`./upload/${info.username}`)
      ctx.body = {
        status: 200,
        message: '获取成功',
        data: {
          list: dir
        }
      }
    }
  }
}
